package com.study.customserializable;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class StringList implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private transient int size = 0;
	private transient Entry head = null;
	private transient Entry previous = null;
	private transient Entry next = null;
	
	private String newStrForNewVersionTest = "test";
	
	private static class Entry{
		String data;
		Entry next;
		Entry previous;
	}
	
	public final void add(String s){
		size ++;
		
		if(head == null){
			head = new Entry();
			head.data = s;
			return;
		}
		
		if(previous == null){
			previous = head;
		}
		if(next == null){
			next = head.next;
		}
		while(next != null){
			previous = next;
			next = next.next;
		}
		
		Entry last = new Entry();
		previous.next = last;
		last.previous = previous;
		last.data = s;
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for(Entry e = head; e != null; e = e.next){
			sb.append(e.data);
		}
		
		if(newStrForNewVersionTest != null && !newStrForNewVersionTest.equals("")){
			sb.append(newStrForNewVersionTest);
		}
		
		return sb.toString();
	}


	private void writeObject(ObjectOutputStream s) throws IOException{
		s.defaultWriteObject();
		s.writeInt(size);
		
		for(Entry e = head; e != null; e = e.next){
			s.writeObject(e.data);
		}
	}
	
	private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException{
		s.defaultReadObject();
		int numElements = s.readInt();
		
		for(int i = 0; i < numElements; i++){
			add((String) s.readObject());
		}
	}
}
